package com.gec.service.impl;

import com.gec.model.system.SysUser;
import com.gec.service.SysMenuService;
import com.gec.service.SysUserService;
import com.gec.system.custom.CustomUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component(value = "userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService,com.gec.system.service.UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;
    //使用主键进行判断,根据用户名获取用户对象
    @Override
    public UserDetails findUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("username = " + username);
        SysUser sysUser= this.sysUserService.getUserInfoUserName(username);
        //从数据库里面获取与给定用户名相对应的对象,如果用户为空,则返回异常
        if(sysUser==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //判断用户的状态
        if(sysUser.getStatus().equals("0")){
            throw new RuntimeException("账号已停止使用");
        }
        //return new CustomUser(sysUser, Collections.emptyList());
        //使用sysUser.getId()从数据库获取用户权限列表
        List<String> userPermit=sysMenuService.findUserPermList(sysUser.getId());
        List<SimpleGrantedAuthority> authorities=new ArrayList<>();
        for (String perm : userPermit) {
            authorities.add(new SimpleGrantedAuthority(perm.trim()));
        }
        return new CustomUser(sysUser, authorities);
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return findUserByUsername(s);
    }
}
